<?php
include_once(ROOTDIR.'include/ap.class.php');
include_once(ROOTDIR.'include/pushmsg.class.php');
class Msg extends Ap {
	public function Message($biz_content, $userid) {
		header ( "Content-Type: text/xml;charset=GBK" );
		////writeLog ( $biz_content );

		//"logon_id":"185****0788","user_name":"*旗"
		$UserInfo = $this->getNode ( $biz_content, "UserInfo" );
		//20880080684764433638664070812640
		$FromUserId = $this->getNode ( $biz_content, "FromUserId" );
		//2015101200425213
		$AppId = $this->getNode ( $biz_content, "AppId" );
		//1449630443192
		$CreateTime = $this->getNode ( $biz_content, "CreateTime" );
		//event
		$MsgType = $this->getNode ( $biz_content, "MsgType" );
		//follow
		$EventType = $this->getNode ( $biz_content, "EventType" );
		//empty
		$AgreementId = $this->getNode ( $biz_content, "AgreementId" );
		$ActionParam = $this->getNode ( $biz_content, "ActionParam" );
		$AccountNo = $this->getNode ( $biz_content, "AccountNo" );

		/*$data = $UserInfo .'^^^^^'. $FromUserId.'^^^^^'. $AppId.'^^^^^'. $CreateTime.'^^^^^|'.$MsgType.'^^^^^|'. $EventType.'^^^^^|'. $AgreementId.'^^^^^|'. $ActionParam.'^^^^^|'. $AccountNo;
		$data = array(
				'content'  => $userid,
				'gcontent' => $data,
				'tim'      => date('Y-m-d H:i:s', time()),
		);

		$this->setdata('errortest', $data);*/

		//读取用户
		$config = $this->getapinfo($userid);

		$push = new push ();
		// 收到用户发送的对话消息
		if ($MsgType == "text") {
			$text = $this->getNode ( $biz_content, "Text" );
			//当用户发送过来内容时，先判断是否为关键词
			//如果是，则优先回复关键词内容，
			//如果不是，则回复设置的消息内容，并且2小时内发只能送一次

			$webinfo = Lxbase::getconfig("web");
			//查询接收到的内容是否为关键词
			$keys = $this->arrdata("keywords, content, type","apreply_key","where userid={$userid}");
			$num = 0;
			foreach ($keys as $k => $v)
			{
				$pos = strpos(str_replace(' ', '', $v['keywords']), $text);
				if($pos !== false)
				{
					$num++;
				}
			}

			//是关键词
			if($num)
			{
				foreach ($keys as $k => $v)
				{
					$pos = strpos(str_replace(' ', '', $v['keywords']), $text);
					if($pos !== false)
					{
						if($v['type'] == 1)
						{
							//图文
							$imgtexts = $this->arrdata("*","apfodder", "where msgid={$v['content']}");

							foreach ($imgtexts as $k => $v)
							{
								$image_text_msg[] = $push->mkImageTextMsg ( $v['title'], $v['abstract'], $webinfo["basehost"]. "api/apmsgtext.php?userid=".$userid."&id=".$v['id'], $v['img_url'], "");
							}
							//发给这个关注的用户
							$biz_content = $push->mkImageTextBizContent ( $FromUserId, $image_text_msg );
						}
						else
						{
							//纯文本
							$text_msg = $push->mkTextMsg ($v['content']);
							// 发给这个关注的用户
							$biz_content = $push->mkTextBizContent ( $FromUserId, $text_msg );
							$biz_content = iconv ( "UTF-8", "GBK//IGNORE", $biz_content );
						}
						break;
					}
				}
			}
			else
			{
				//先去已发送的表中查看是否在2小时内发送过
				$send = $this->viewdata("*","apsend","where userid={$userid} AND sendid={$FromUserId}");
				//如果回复的消息超过2小时，或者从来没有发送过，则发送
				if(!$send)
				{
					//查询要发送的信息
					$msg = $this->viewdata("*","apreply_msg","where userid={$userid}");
					if($msg['type'] ==1)
					{
						//图文
						$imgtexts = $this->arrdata("*","apfodder", "where msgid={$msg['content']}");

						foreach ($imgtexts as $k => $v)
						{
							$image_text_msg[] = $push->mkImageTextMsg ( $v['title'], $v['abstract'], $webinfo["basehost"]. "api/apmsgtext.php?userid=".$userid."&id=".$v['id'], $v['img_url'], "");
						}
						//发给这个关注的用户
						$biz_content = $push->mkImageTextBizContent ( $FromUserId, $image_text_msg );
					}
					else
					{
						//纯文本
						$text_msg = $push->mkTextMsg ($msg['content']);
						// 发给这个关注的用户
						$biz_content = $push->mkTextBizContent ( $FromUserId, $text_msg );
						$biz_content = iconv ( "UTF-8", "GBK//IGNORE", $biz_content );
					}
					$into = array(
							'userid' => $userid,
							'sendid' => $FromUserId,
							'time'   => date('Y-m-d H:i:s', time()),
					);
					$this->setdata("apsend",$into);

				}
				elseif(strtotime($send['time'])+2*3600 <=time())
				{
					//查询要发送的信息
					$msg = $this->viewdata("*","apreply_msg","where userid={$userid}");
					if($msg['type'] ==1)
					{
						//图文
						$imgtexts = $this->arrdata("*","apfodder", "where msgid={$msg['content']}");

						foreach ($imgtexts as $k => $v)
						{
							$image_text_msg[] = $push->mkImageTextMsg ( $v['title'], $v['abstract'], $webinfo["basehost"]. "api/apmsgtext.php?userid=".$userid."&id=".$v['id'], $v['img_url'], "");
						}
						//发给这个关注的用户
						$biz_content = $push->mkImageTextBizContent ( $FromUserId, $image_text_msg );
					}
					else
					{
						//纯文本
						$text_msg = $push->mkTextMsg ($msg['content']);
						// 发给这个关注的用户
						$biz_content = $push->mkTextBizContent ( $FromUserId, $text_msg );
						$biz_content = iconv ( "UTF-8", "GBK//IGNORE", $biz_content );
					}

					$this->updata('apsend',array('time' => date('Y-m-d H:i:s', time())),"where userid={$userid} AND sendid={$FromUserId}");
				}
			}

			$push->sendRequest ( $biz_content, $config );

			// 日志记录
			//file_put_contents ( "log.txt", $return_msg . "\r\n", FILE_APPEND );
		}
		
		// 接收用户发送的 图片消息
		if ($MsgType == "image") {
			
			$mediaId = $this->getNode ( $biz_content, "MediaId" );
			$format = $this->getNode ( $biz_content, "Format" );
			
			$biz_content = "{\"mediaId\":\"" . $mediaId . "\"}";
			
			$fileName = realpath ( "img" ) . "/$mediaId.$format";
			// 下载保存图片
			$push->downMediaRequest ( $biz_content, $config );
			
			//writeLog ( "收到的图片路径：" . $fileName );
			
			$text_msg = $push->mkTextMsg ( "你好，图片已接收。" );
			
			// 发给这个关注的用户
			$biz_content = $push->mkTextBizContent ( $FromUserId, $text_msg );
			$biz_content = iconv ( "UTF-8", "GBK//IGNORE", $biz_content );

			// $push->sendMsgRequest ( $biz_content, $config );
			//$push->sendRequest ( $biz_content, $config );
			// 日志记录
			//writeLog ( "发送对话消息返回：" . $return_msg );
		}

		// 收到用户发送的关注消息
		if ($EventType == "follow") {
			// 处理关注消息
			// 一般情况下，可推送一条欢迎消息或使用指导的消息。
			//纯文本信息
			$text_msg = $push->mkTextMsg("欢迎关注！");

			// 发给这个关注的用户
			$biz_content = $push->mkTextBizContent($FromUserId, $text_msg);
			$biz_content = iconv("UTF-8", "GBK//IGNORE", $biz_content);

			//$push->sendRequest($biz_content, $config);

		}
		elseif ($EventType == "unfollow") {
			// 处理取消关注消息
		}
		elseif ($EventType == "enter") {
			
			// 处理进入消息，扫描二维码进入,获取二维码扫描传过来的参数
			
			$arr = json_decode ( $ActionParam );
			if ($arr != null) {
				//writeLog ( "二维码传来的参数：" . var_export ( $arr, true ) );
				
				$sceneId = $arr->scene->sceneId;
				//writeLog ( "二维码传来的参数,场景ID：" . $sceneId );
				// 这里可以根据定义场景ID时指定的规则，来处理对应事件。
				// 如：跳转到某个页面，或记录从什么来源(哪种宣传方式)来关注的本服务窗
			}
			// 处理关注消息
			// 一般情况下，可推送一条欢迎消息或使用指导的消息。
			// 如：
			$image_text_msg1 = $push->mkImageTextMsg ( "标题，进入服务窗", "描述：进入服务窗", "http://wap.taobao.com", "", "loginAuth" );
			// $image_text_msg2 = $push->mkImageTextMsg ( "标题", "描述", "http://wap.taobao.com", "https://i.alipayobjects.com/e/201310/1H9ctsy9oN_src.jpg", "loginAuth" );
			// 组装多条图文信息
			$image_text_msg = array (
					$image_text_msg1 
			// $image_text_msg2
						);
			
			// 发给这个关注的用户
			$biz_content = $push->mkImageTextBizContent ( $FromUserId, $image_text_msg );
			
			$return_msg = $push->sendRequest ( $biz_content );
			// 日志记录
			//writeLog ( "发送消息返回：" . var_export ( $return_msg, true ) );
		}
		elseif ($EventType == "click") {
			// 处理菜单点击的消息
			// 在服务窗后台配置一个菜单，菜单类型为调用服务，菜单参数为sendmsg，用户点击次菜单后，就会调用到这里

			$param = substr($ActionParam, 5);

			$info = $this->arrdata("*","apfodder","where msgid={$param}");
			$webinfo = Lxbase::getconfig("web");
			foreach ($info as $k => $v)
			{
				$image_text_msg[] = $push->mkImageTextMsg ( $v['title'], $v['abstract'], $webinfo["basehost"]. "api/apmsgtext.php?userid=".$userid."&id=".$v['id'], $v['img_url'], "");
			}

			// 发给这个关注的用户
			$biz_content = $push->mkImageTextBizContent ( $FromUserId, $image_text_msg );

			$push->sendRequest ( $biz_content, $config );

		}
		
		// 给支付宝返回ACK回应消息，不然支付宝会再次重试发送消息,再调用此方法之前，不要打印输出任何内容
		echo self::mkAckMsg ( $FromUserId, $config );
		exit ();
	}

	public function	mkAckMsg($toUserId, $config) {
		//$as = new AlipaySign ();
		//require 'config.php';
		$response_xml = "<XML><ToUserId><![CDATA[" . $toUserId . "]]></ToUserId><AppId><![CDATA[" . $config ['appid'] . "]]></AppId><CreateTime>" . time () . "</CreateTime><MsgType><![CDATA[ack]]></MsgType></XML>";
		
		$return_xml = $this->sign_response ( $response_xml, $this->charset, $config ['merchant_private_key'] );
		//writeLog ( "response_xml: " . $return_xml );
		return $return_xml;
	}
	
	/**
	 * 直接获取xml中某个结点的内容
	 *
	 * @param unknown $xml        	
	 * @param unknown $node        	
	 */
	public function getNode($xml, $node) {
		$xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>" . $xml;
		$dom = new DOMDocument ( "1.0", "GBK" );
		$dom->loadXML ( $xml );
		$event_type = $dom->getElementsByTagName ( $node );
		return $event_type->item ( 0 )->nodeValue;
	}
}